package com.lgmshare.k3.ui.webview;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;

import androidx.appcompat.widget.Toolbar;

import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.lgmshare.component.logger.Logger;
import com.lgmshare.k3.R;
import com.lgmshare.k3.ui.base.BaseActivity;

/**
 * 视频播放使用
 *
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2016/7/12 10:58
 */
public class VideoWebViewActivity extends BaseActivity {

    public static final String EXTRA_WEB_TITLE = "web_title";
    public static final String EXTRA_WEB_URL = "web_url";

    private VideoEnabledWebView mVideoEnabledWebView;
    private VideoEnabledWebChromeClient mWebChromeClient;

    protected String mPageTitle;
    protected String mPageUrl;

    private TextView toolbar_title;

    @Override
    protected int onBindLayoutResId() {
        return R.layout.activity_webview_video;
    }

    @Override
    protected void initData() {
        mPageTitle = getIntent().getStringExtra(EXTRA_WEB_TITLE);
        mPageUrl = getIntent().getStringExtra(EXTRA_WEB_URL);
    }


    @Override
    protected void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar_title.setText(mPageTitle);
        // Save the web view
        mVideoEnabledWebView = findViewById(R.id.webView);
        initWebSetting(mVideoEnabledWebView);
        // Initialize the VideoEnabledWebChromeClient and set event handlers
        View nonVideoLayout = findViewById(R.id.nonVideoLayout); // Your own view, read class comments
        ViewGroup videoLayout = findViewById(R.id.videoLayout); // Your own view, read class comments
        //noinspection all
        View loadingView = getLayoutInflater().inflate(R.layout.layout_loading_video, null); // Your own view, read class comments
        mWebChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, mVideoEnabledWebView) // See all available constructors...
        {
            // Subscribe to standard events, such as onProgressChanged()...
            @Override
            public void onProgressChanged(WebView view, int progress) {
                // Your code...
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        };
        mWebChromeClient.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback() {
            @Override
            public void toggledFullscreen(boolean fullscreen) {
                // Your code to handle the full-screen change, for example showing and hiding the title bar. Example:
                if (fullscreen) {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14) {
                        // noinspection all
                        getWindow().getDecorView().setSystemUiVisibility(
                                View.SYSTEM_UI_FLAG_LOW_PROFILE);
                    }
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    WindowManager.LayoutParams attrs = getWindow().getAttributes();
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14) {
                        // noinspection all
                        getWindow().getDecorView().setSystemUiVisibility(
                                View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }

            }
        });
        mVideoEnabledWebView.setWebChromeClient(mWebChromeClient);
        // Call private class InsideWebViewClient
        mVideoEnabledWebView.setWebViewClient(new InsideWebViewClient());

        // Navigate everywhere you want, this classes have only been tested on YouTube's mobile site
        mVideoEnabledWebView.loadUrl(mPageUrl);
    }

    @Override
    protected void initLoad() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoEnabledWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVideoEnabledWebView.onPause();
    }

    @Override
    protected void onDestroy() {
        mVideoEnabledWebView.destroy();
        super.onDestroy();
    }

    private void initWebSetting(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        // UserInfo settings
        //settings.setUserAgentString("Android");//慎用！在加载一些界面的时候会无法加载
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(false); // 设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultTextEncodingName("UTF-8");//编码方式
        webSettings.setDefaultFontSize(16);//默认字体大小
        webSettings.setDomStorageEnabled(true);//手动开启DOM Storage
        /**
         * 用WebView显示图片，可使用这个参数 设置网页布局类型：
         * 1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
         * 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */
        //其中关键是以下设置属性
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    }

    private class InsideWebViewClient extends WebViewClient {
        @Override
        // Force links to be opened inside WebView and not in Default Browser
        // Thanks http://stackoverflow.com/a/33681975/1815624
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    /**
     * 当横竖屏切换时会调用该方法
     *
     * @author
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Logger.d(TAG, " 现在是横屏");
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Logger.d(TAG, " 现在是竖屏");
        }
    }

    @Override
    public void onBackPressed() {
        // Notify the VideoEnabledWebChromeClient, and handle it ourselves if it doesn'setTag handle it
        if (!mWebChromeClient.onBackPressed()) {
            if (mVideoEnabledWebView.canGoBack()) {
                mVideoEnabledWebView.goBack();
            } else {
                // Standard back button implementation (for example this could close the app)
                super.onBackPressed();
            }
        }
    }

}
